import pandas as pd
from model.model import ParserGroup, ParserLib, ParserMap, ParserRule
from package.connector.sql_db import db
from common.collector_common.parser import Parser, ExtractProcessor, GroupParser


class ParserGroupView(ParserGroup):
    
    @classmethod
    def verify(cls, session, id, data):
        df = pd.DataFrame([data])
        items = cls.get_items(session, filter_=[cls.id == id])
        groups = [{'id': group.id, 
                   'rules': [{'id': rule.id, 
                              'identifiers': rule.identifiers} for rule in group.rules]} for group in items]
        rule_config_map = {rule.id: {'model_id': rule.model_id, 'extract':rule.extract, 'transforms': rule.transforms } 
                           for group in items for rule in group.rules}
        datas = GroupParser.group_parser(df, groups, rule_config_map)
        if datas:
            return datas[0].to_dict('records')
        return {}

    @classmethod
    def delete_groups(cls, session, filter_):
        pass


class ParserRuleView(ParserRule):

    @classmethod
    def extract_pattern(cls, data, extract, field='_raw'):
        return ExtractProcessor.extract_pattern(data[field], configure=extract['configure'], pattern=extract['pattern'])

    @classmethod
    def extract_verify(cls, data, extract, field='_raw'):
        df = pd.DataFrame([data])
        df = Parser.extract(df, field=field, pattern=extract['pattern'])
        return df.to_dict('records')[0]

    @classmethod
    def transform_verify(cls, data, transforms):
        df = pd.DataFrame([data])
        df = Parser.transform(df, transforms=transforms)
        return df.to_dict('records')[0]


class ParserLibView(ParserLib):
    pass


class ParserMapView(ParserMap):
    pass
